local args = { ... }
local fuelSlot = 1
local removeObstacles = false
local refuelingTurtle = "Low fuel detected, refueling"
local outOfFuel = "Turtle out of fuel, waiting for refuel"
local obstacleEncountered = "Obstacle encountered, waiting"
local author = "Kevin Scroggins"
local nickname = "nitro glycerine"
local email = "nitro404@gmail.com
local website = "http://www.nitro404.com"

function checkFuel()
  if turtle.getItemCount(fuelSlot) == 0 then
    print(outOfFuel)
    
    while turtle.getItemCount(fuelSlot) == 0 do
      os.sleep(1)
    end
  end
  
  if turtle.getFuelLevel() < 15 then
    print(refuelingTurtle)
    turtle.select(fuelSlot)
    if turtle.refuel(1) ~= true then
      print(outOfFuel)
      
      while turtle.refuel(1) ~= true do
        os.sleep(1)
      end
    end
    
    checkFuel()
  end
end

function forward(d)
  if d == nil then
    d = 1
  elseif d < 1 then
    return
  end
  
  for i = 0, d - 1, 1 do
    checkFuel()
    
    if turtle.forward() ~= true then
      print(obstacleEncountered)
      
      while turtle.forward() ~= true do
        checkFuel()
        
        if removeObstacles == true then
          turtle.dig()
        end
        
        os.sleep(0.5)
      end
    end
  end
  
  checkFuel()
end

function back(d)
  if d == nil then
    d = 1
  elseif d < 1 then
    return
  end
  
  for i = 0, d - 1, 1 do
    checkFuel()
    
    if turtle.back() ~= true then
      print(obstacleEncountered)
      
      while turtle.back() ~= true do
        checkFuel()
        
        os.sleep(0.5)
      end
    end
  end
  
  checkFuel()
end

function up(d)
  if d == nil then
    d = 1
  elseif d < 1 then
    return
  end
  
  for i = 0, d - 1, 1 do
    checkFuel()
    
    if turtle.up() ~= true then
      print(obstacleEncountered)
      
      while turtle.up() ~= true do
        checkFuel()
        
        if removeObstacles == true then
          turtle.digUp()
        end
        
        os.sleep(0.5)
      end
    end
  end
  
  checkFuel()
end

function down(d)
  if d == nil then
    d = 1
  elseif d < 1 then
    return
  end
  
  for i = 0, d - 1, 1 do
    checkFuel()
    
    if turtle.down() ~= true then
      print(obstacleEncountered)
      
      while turtle.down() ~= true do
        checkFuel()
        
        if removeObstacles == true then
          turtle.digDown()
        end
        os.sleep(0.5)
      end
    end
  end
  
  checkFuel()
end

function left(n)
  if n == nil then
    n = 1
  elseif n < 1 then
    return
  end
  
  for i = 0, n - 1, 1 do
    turtle.turnLeft()
  end
end

function right(n)
  if n == nil then
    n = 1
  elseif n < 1 then
    return
  end
  
  for i = 0, n - 1, 1 do
    turtle.turnRight()
  end
end

function r()
  if #args == 0 then
    right()
  elseif #args == 1 then
    local n = tonumber(args[1])
    if n ~= nil then
      right(n)
    end
  else
    error("Usage: r <amount>")
  end
end

r()
